package com.yeskery.nut.bean;

import com.yeskery.nut.annotation.web.Controller;
import com.yeskery.nut.annotation.web.RestController;
import com.yeskery.nut.aop.ProxyType;
import com.yeskery.nut.application.NutApplication;

/**
 * Web应用上下文
 * @author YESKERY
 * 2023/10/16
 */
public class WebApplicationContext extends AnnotationApplicationContext {

    /**
     * 构建基于注解的应用上下文
     * @param nutApplication Nut应用对象
     */
    public WebApplicationContext(NutApplication nutApplication) {
        super(nutApplication, nutApplication.getApplicationContext());
    }

    /**
     * 注册controller bean
     * @param beanClass bean类型
     */
    public void registerControllerBean(Class<?> beanClass) {
        if (!isControllerAnnotationPresent(beanClass)) {
            return;
        }
        BeanDefinition beanDefinition = getComponentBeanDefinition(beanClass, getControllerBeanName(beanClass),
                true, false, ProxyType.AUTO);
        if (beanDefinition == null) {
            throw new BeanException("Bean Definition Not Found.");
        }
        registerBean(beanDefinition);
    }

    /**
     * 获取是否有Controller注解
     * @param beanClass bean类型
     * @return 是否有Controller注解
     */
    private boolean isControllerAnnotationPresent(Class<?> beanClass) {
        return beanClass.isAnnotationPresent(Controller.class) || beanClass.isAnnotationPresent(RestController.class);
    }

    /**
     * 获取controller bean名称
     * @param beanClass bean类型
     * @return controller bean名称
     */
    private String getControllerBeanName(Class<?> beanClass) {
        Controller controller = beanClass.getAnnotation(Controller.class);
        if (controller != null) {
            return controller.value();
        }
        RestController restController = beanClass.getAnnotation(RestController.class);
        if (restController != null) {
            return restController.value();
        }
        return "";
    }
}
